import axios from 'axios';
import {Message} from "element-ui";

axios.interceptors.response.use(success => {
    if (success.data) {
        if(success.data.code != 200){
            if (success.data.msg) {
                Message.error({message: success.data.msg});
                return;
            }
        }
        if (success.data.msg) {
            Message.success({message: success.data.msg});
        }
        return success.data;
    }
}, error => {
    if (error.response) {
        if (error.response.status == 401) {
            Message.error({message: '用户未认证'})
        } else if (error.response.status == 403) {
            Message.error({message: '用户权限不足'})
        } else if (error.response.status == 404) {
            Message.error({message: '资源找不到'})
        } else if (error.response.status == 504) {
            Message.error({message: '网关超时'})
        } else {
            Message.error({message: '未知错误'})
        }
    }
    return;
})

let base = '';

export const getRequest = (url,params) => {
    return axios({
        method:'get',
        url : `${base}${url}`,
        params : params
    })
}

export const postRequest = (url,params) => {
    return axios({
        method:'post',
        url : `${base}${url}`,
        data : params
    })
}

export const postKeyValueRequest = (url,params) => {
    return axios({
        method:'post',
        url : `${base}${url}`,
        data : params,
        transformRequest : [function (data) {
            let result = '';
            for(let i in data){
                result += encodeURIComponent(i)+'='+encodeURIComponent(data[i])+'&';
            }
            return result;
        }],
        header : {
            'Content-type' : 'application/x-www-form-urlencoded'
        }
    })
}

export const putRequest = (url,params) => {
    return axios({
        method:'put',
        url : `${base}${url}`,
        data : params
    })
}

export const delRequest = (url,params) => {
    return axios({
        method:'delete',
        url : `${base}${url}`,
        params : params
    })
}